import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { permissionRouter } from './permission'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: '/layout'
    },
    {
        path: '/login',
        name: 'login',
        meta: {
            title: '用户登录'
        },
        component: () => import('@/views/login/index')
    },
    {
        path: '/register',
        name: 'register',
        meta: {
            title: '用户注册'
        },
        component: () => import('@/views/register/index')
    },
    {
        path: '/courseBBS',
        name: 'courseBBS',
        meta: {
            title: '课程论坛'
        },
        component: () => import('@/views/course/courseBBS/index')
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})


// 路由守卫，防止无token访问url
const NO_NEED = ['/login', '/register']


router.beforeEach( async (to, from, next) => {
    if (NO_NEED.includes(to.path)) {
        document.title = to.meta.title;
        next()
    } else {
        let token = store.getters.token
        if (!token) {
            document.title = to.meta.title;
            next('/login')
        } else {
            let routeMenu = store.getters.asyncRoutes
            if (routeMenu.length === 0) {
                document.title = to.meta.title;
                await store.dispatch('permission/getRoute', sessionStorage.getItem('role'))
                permissionRouter()
                next({...to, replace: true})
            } else {
                if (to.path === '/courseBBS' && store.getters.userInfo.userType !== 'administrator' && store.getters.userInfo.courseIds === '') {
                    Message.warning('您还没有相关课程')
                    next(from.path)
                } else {
                    document.title = to.meta.title;
                    next()
                }
            }

        }
    }
})

export default router
